package com.quanyan.user.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.user.mapper.TbAppBannerMapper;
import com.quanyan.user.mapper.TbUserMapper;
import com.quanyan.user.model.db.TbAppBanner;
import com.quanyan.user.model.db.TbAppBannerExample;
import com.quanyan.user.model.db.TbUser;
import com.quanyan.user.model.db.TbUserExample;
import com.quanyan.user.model.vo.request.ReqAppBannerInfo;
import com.quanyan.user.model.vo.response.RespAppBanner;
import com.quanyan.user.service.UserAppBannerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by slong.guo on 2016/12/13.
 */
@Service
public class UserAppBannerServiceImpl implements UserAppBannerService {

    private static final int BANNER_HOMEPAGE = 1;
    private static final int BANNER_VENUE = 2;
    private static final int BANNER_DIALOG_HOMEPAGE = 3;
    private static final int BANNER_DIALOG_STADIUM = 4;
    private static final int BANNER_TALENT_CHANNEL = 5; //达人
    private static final int BANNER_MATCH = 6; //赛事
    @Autowired
    private TbAppBannerMapper tbAppBannerMapper;
    @Autowired
    private TbUserMapper tbUserMapper;


//    private static final int BANNER_DIALOG_TALENT_CHANNEL = 6;
    @Value("${filtered.bannerIDs}")
    private String filteredActivityIDs;

    /**
     * 获取用户banner信息
     *
     * @param type
     * @param city
     * @return
     */
    @Override
    public APIResponse<List<RespAppBanner>> getBannerInfo(int uid, int type, int city, int sportType, int competition, Integer platformType, String platform_ver) {

        if (type < BANNER_HOMEPAGE || type > BANNER_MATCH) {
            return APIResponse.returnFail("参数错误");
        }
        if ((type == BANNER_HOMEPAGE || type == BANNER_VENUE) && city <= 0) {
            return APIResponse.returnFail("参数错误");
        }

//        if (type == BANNER_MATCH && (sportType < 0 || competition < 0)) {
//            return APIResponse.returnFail("参数错误");
//        }

        List<RespAppBanner> respAppBannerList;

        if (type == BANNER_HOMEPAGE) {
            respAppBannerList = getAppBannerList(uid, 1, 1, city, sportType, competition, 0);
        } else if (type == BANNER_VENUE) {
            respAppBannerList = getAppBannerList(uid, 2, 1, city, sportType, competition, 0);
        } else if (type == BANNER_DIALOG_HOMEPAGE) {
            respAppBannerList = getAppBannerList(uid, 1, 2, city, sportType, competition, 0);
        } else if (type == BANNER_DIALOG_STADIUM) {
            respAppBannerList = getAppBannerList(uid, 2, 2, city, sportType, competition, 0);
        } else if (type == BANNER_TALENT_CHANNEL) {
            respAppBannerList = getAppBannerList(uid, 3, 1, city, sportType, competition, 0);
        } else if (type == BANNER_MATCH) {
            respAppBannerList = getAppBannerList(uid, 4, 1, city, sportType, competition, 0);
        } else {
            return APIResponse.returnFail("请求参数有误");
        }

        if (uid > 0) {
            updateUserLoginTime(uid);
        }

        if (platformType != null && platform_ver != null && platformType.equals(1) && platform_ver.equals("2.6")) {
            List<RespAppBanner> appBanners = new ArrayList<>();
            String[] ids = filteredActivityIDs.split(",");
            Set<String> idSet = new HashSet<>(Arrays.asList(ids));
            for (RespAppBanner banner : respAppBannerList) {
                if (!idSet.contains("" + banner.getId())) {
                    appBanners.add(banner);
                }
            }

            return APIResponse.returnSuccess(appBanners);
        } else {
            return APIResponse.returnSuccess(respAppBannerList);
        }
    }


    @Override
    public APIResponse<List<RespAppBanner>> getBannerInfoNew(int uid, ReqAppBannerInfo reqInfo) {
        int type = reqInfo.getType();
        int city = reqInfo.getCity();
        int sportType = reqInfo.getSportType();
        int competition = reqInfo.getCompetition();
        int larkAppId = reqInfo.getLarkAppId();

        if (type < BANNER_HOMEPAGE || type > BANNER_MATCH) {
            return APIResponse.returnFail("参数错误");
        }
        if ((type == BANNER_HOMEPAGE || type == BANNER_VENUE) && city <= 0) {
            return APIResponse.returnFail("参数错误");
        }

        List<RespAppBanner> respAppBannerList;
        if (type == BANNER_HOMEPAGE) {
            respAppBannerList = getAppBannerList(uid, 1, 1, city, sportType, competition, larkAppId);
        } else if (type == BANNER_VENUE) {
            respAppBannerList = getAppBannerList(uid, 2, 1, city, sportType, competition, larkAppId);
        } else if (type == BANNER_DIALOG_HOMEPAGE) {
            respAppBannerList = getAppBannerList(uid, 1, 2, city, sportType, competition, larkAppId);
        } else if (type == BANNER_DIALOG_STADIUM) {
            respAppBannerList = getAppBannerList(uid, 2, 2, city, sportType, competition, larkAppId);
        } else if (type == BANNER_TALENT_CHANNEL) {
            respAppBannerList = getAppBannerList(uid, 3, 1, city, sportType, competition, larkAppId);
        } else if (type == BANNER_MATCH) {
            respAppBannerList = getAppBannerList(uid, 4, 1, city, sportType, competition, larkAppId);
        } else {
            return APIResponse.returnFail("请求参数有误");
        }

        if (uid > 0) {
            updateUserLoginTime(uid);
        }

        return APIResponse.returnSuccess(respAppBannerList);

    }

    /**
     * 查询数据库banner信息
     *
     * @param module
     * @param imageType
     * @param city
     * @return
     */
    public List<RespAppBanner> getAppBannerList(int uid, int module, int imageType, int city, int sportType, int competition, int larkAppId) {
        TbAppBannerExample example = new TbAppBannerExample();
        TbAppBannerExample.Criteria criteria = example.createCriteria();
        criteria.andModuleEqualTo((byte) module);
        criteria.andImgtypeEqualTo((byte) imageType);
        criteria.andStarttimeLessThanOrEqualTo(DateUtils.getSecondTimestampOne(new Date()));
        criteria.andEndtimeGreaterThanOrEqualTo(DateUtils.getSecondTimestampOne(new Date()));

        if (sportType >= 0 && competition >= 0) {
            criteria.andSportTypeEqualTo((byte) sportType);
            criteria.andCompetitionEqualTo((byte) competition);
        }

        if (larkAppId > 0) {
            criteria.andAppChannelEqualTo(larkAppId);
        }

        example.setOrderByClause("seq desc, starttime desc");

        List<TbAppBanner> appBannerList = tbAppBannerMapper.selectByExampleWithBLOBs(example);
        List<RespAppBanner> respAppBannerList = new ArrayList<>();
        for (TbAppBanner tbAppBanner : appBannerList) {
            String cityStr = tbAppBanner.getCitys();
            if (StringUtils.isBlank(cityStr)) {
                //citys字段为null或为空的话,不处理,这种情况一般不会出现
                continue;
            }

            String limit_uids = tbAppBanner.getLimitUids();
            boolean uid_filtered = false;
            if (StringUtils.isBlank(limit_uids)) {
                uid_filtered = true;
            } else {
                String[] uids = limit_uids.split(",");
                for (String uidStr : uids) {
                    if (uidStr.equals(String.valueOf(uid))) {
                        uid_filtered = true;
                        break;
                    }
                }
            }

            if (!uid_filtered) {
                continue;
            }

            if (city == 0) {
                respAppBannerList.add(new RespAppBanner(tbAppBanner));
            } else {
                String[] citys = cityStr.split(",");
                Set<String> citySet = new HashSet<>(Arrays.asList(citys));
                if (citySet.contains(String.valueOf(city))) {
                    respAppBannerList.add(new RespAppBanner(tbAppBanner));
                }
            }
        }
        return respAppBannerList;
    }

    @Async
    private void updateUserLoginTime(int uid) {
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(uid);

        TbUser record = new TbUser();
        record.setId(uid);
        record.setLoginTime(new Date());

        tbUserMapper.updateByExampleSelective(record, example);
    }


}
